<?php
class Tourismgoodsbase extends CS_Controller
{
    public function _init()
    {
        $this->load->library('pagination');
        $this->load->model('region_model', 'region');
        $this->load->model('tourism_goods_image_model', 'tourism_goods_image');
        $this->load->model('tourism_goods_base_model', 'tourism_goods_base');
        $this->load->model('tourism_goods_attr_model', 'tourism_goods_attr');
        $this->load->model('tourism_goods_category_model', 'tourism_goods_category');
        $this->load->model('tourism_goods_category_additive_model', 'tourism_goods_category_additive');
        $this->load->model('tourism_goods_category_attribute_model', 'tourism_goods_category_attribute');
        $this->load->model('tourism_goods_category_spec_model', 'tourism_goods_category_spec');
        $this->load->model('tourism_goods_brand_model', 'tourism_goods_brand');
        $this->load->model('tourism_freight_template_model', 'tourism_freight_template');
        $this->load->model('tourism_provider_category_model','tourism_provider_category');
        $this->load->model('user_type_model', 'user_type');
        $this->load->model('tourism_goods_profit_model', 'tourism_goods_profit');
        $this->load->model('tourism_profit_rate_model','tourism_profit_rate');
        $this->load->model('user_model', 'user');
    }

    /**
     * 产品列表
     * @param int $pg
     */
    public function grid($pg = 1)
    {
        $getData = $this->input->get();
        $getData['uid'] = $this->uid;
        $page_num = 15;
        $num = ($pg - 1) * $page_num;
        $config['first_url'] = base_url('tourismgoodsbase/grid') . $this->pageGetParam($this->input->get());
        $config['suffix'] = $this->pageGetParam($this->input->get());
        $config['base_url'] = base_url('tourismgoodsbase/grid');
        $config['total_rows'] = $this->tourism_goods_base->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['page_list'] = $this->tourism_goods_base->page_list($page_num, $num, $getData);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['is_check'] = array('1' => '待审核', '2' => '通过审核', '3' => '未通过审核');
        if (isset($getData['is_on_sale'])) {
            unset($getData['is_on_sale']);
        }
        if (isset($getData['is_beizhu'])) {
            unset($getData['is_beizhu']);
        }
        if (isset($getData['uid'])) {
            unset($getData['uid']);
        }
        $data['urlparams'] = $this->pageGetParam($getData);
        $this->load->view('tourismgoodsbase/grid', $data);
    }

    /**
     * 产品下架
     * @param unknown $goods_id
     */
    public function upOrDown($goods_id, $isOnSale)
    {
        switch ($isOnSale) {
            case 1: $status = 2; break;
            case 2: $status = 1; break;
            default:break;
        }
        $params['goods_id'] = $goods_id;
        $params['uid'] = $this->uid;
        $params['is_on_sale'] = $status;
        
        $this->db->trans_start();
        $result = $this->tourism_goods_base->updateGoodsStatus($params);
        $this->db->trans_complete();
        
        if ($this->db->trans_status() === TRUE) {
            $this->success('tourismgoodsbase/grid', '', $isOnSale==1?'商品已下架':'商品已上架');
        } else {
            $this->error('tourismgoodsbase/grid', '', '商品下架失败');
        }
    }
    
    public function isDelete($goods_attr_id)
    {
        $params['goods_attr_id'] = $goods_attr_id;
        $params['uid'] = $this->uid;
        $params['logic_delete'] = 2;
        $this->db->trans_start();
        $result = $this->tourism_goods_attr->updateGoodsDelete($params);
        $this->db->trans_complete();
        if ($this->db->trans_status() === TRUE) {
            $this->success('tourismgoodsbase/grid', '', '商品删除成功');
        } else {
            $this->error('tourismgoodsbase/grid', '', '商品删除失败');
        }
    }

    /*
     *旅游商品添加第一步 为产品增加类别
     * author laona
     */
    public function addstep1()
    {
        $category = $this->tourism_goods_category->page_list();
        $data['cate'] = $category->result();
        $this->load->view('tourismgoodsbase/addstep1', $data);
    }

     /**
     * 旅游商品添加第二步 添加基本信息
     * author laona
     */
    public function addstep2()
    {
        $class_c = (int)$this->input->get('class_c');
        if (!$this->tourism_goods_category->classValidate($class_c)) {
            $this->error('tourismgoodsbase/addstep1', '', '请选择完整的类别');
        }
        $data['attribute'] = $this->tourism_goods_category_attribute->getAttributeByCategoryId($class_c); //属性规格信息
        $data['additive'] = $this->tourism_goods_category_additive->getAdditive($class_c); //附加属性信息

        $data['brand'] = $this->tourism_goods_brand->getBrand($class_c);//品牌信息
        $data['category'] = $this->tourism_goods_category->getCategoryByLastId($class_c);//类别信息
        //获取运费模板信息
        $data['transport'] = $this->tourism_freight_template->getTransport($this->uid);
        $data['providerCategory'] = $this->tourism_provider_category->providerCategoryByUid($this->uid);
        $data['profitRate'] = $this->tourism_profit_rate->findByParams(array('uid'=>['in' => [$this->uid,0]]),'rate_id,uid,name',null,'rate_id');
        $this->load->view('tourismgoodsbase/addstep2', $data);
    }

     /**
     * 后台商品添加处理
     * author laona
     * */
    public function addPost()
    {
        $error = $this->validate();
        if (!empty($error)) {
            $this->error('tourismgoodsbase/addstep1', '', $error);
        }
        $postData = $this->input->post();
        $postData['uid'] = $this->uid;

        $this->db->trans_begin();
        $goodsId = $this->tourism_goods_base->insertGoodsBase($postData);
        $attrId = $this->tourism_goods_attr->insertGoodsAttr($goodsId, $postData);
        if ($goodsId && $attrId && $this->db->trans_status() === TRUE) {
            $this->db->trans_commit();
            $this->success('tourismgoodsbase/grid', '', '保存成功！');
        } else {
            $this->db->trans_rollback();
            $this->error('tourismgoodsbase/add', '', '保存失败！');
        }
    }
    
    public function validate()
    {
        $error = array();
        if ($this->validateParam($this->input->post('goods_name'))) {
            $error[] = '名称不能为空';
        }
        if ($this->validateParam($this->input->post('wap_goods_desc'))) {
            $error[] = '详情不能为空';
        }
        if ($this->validateParam($this->input->post('is_on_sale'))) {
            $error[] = '上下架不能为空';
        }
        if ($this->validateParam($this->input->post('market_price'))) {
            $error[] = '市场售价不能为空';
        }
        if ($this->validateParam($this->input->post('shop_price'))) {
            $error[] = '销售价不能为空';
        }
        if ($this->validateParam($this->input->post('supply_price'))) {
            $error[] = '供应价不能为空';
        }
        if ($this->input->post('supply_price') > $this->input->post('shop_price')) {
            $error[] = '供应价不能大于销售价';
        }
        if ($this->input->post('shop_price') > $this->input->post('market_price')) {
            $error[] = '销售价不能大于市场售价';
        }
        if ($this->validateParam($this->input->post('goods_num'))) {
            $error[] = '总库存数不能为空';
        }
        if ($this->validateParam($this->input->post('detail'))) {
            $error[] = '详细地址不能为空';
        }
        $cost = $this->input->post('transport_cost');
        if (isset($cost)) {
            if (!is_numeric($cost) || (int)$cost < 0) {
                $error[] = '邮费必须为不小于零的数字';
            }
        }
        
        //地区
        $regionids = array($this->input->post('province_id'), $this->input->post('city_id'), $this->input->post('district_id'));
        $region = $this->region->getByRegionIds($regionids);
        if ($region->num_rows() < 3) {
            $error[] = '城市地区请填写完整。';
        }
        $regionNames = array();
        foreach ($region->result() as $item) {
            $regionNames[] = $item->region_name;
        }
        $_POST['detail'] = $regionNames[0] .' '.$regionNames[1].' '.$regionNames[2].' '.($this->input->post('detail') ? $this->input->post('detail') : '　');
        return $error;
    }
    
     /**
     * 商品信息修改
     * @param unknown $goods_attr_id
     */
    public function edit($goods_attr_id)
    {
        $result = $this->tourism_goods_base->getGoodsAttr($goods_attr_id);
        if ($result->num_rows() < 0) {
            $this->error('tourismgoods/grid', '', '找不到产品相关信息！');
        }
        $goodsBase = $result->row();
        $data['result'] = $goodsBase;
        //获取附加属性
        $data['additive'] = $this->tourism_goods_category_additive->getAdditive($goodsBase->category_id);
        //获取分类信息 全称
        $data['category'] = $this->tourism_goods_category->getCategoryByLastId($goodsBase->category_id);
        //获取
        $data['brand'] = $this->tourism_goods_brand->getBrand($goodsBase->category_id);
        $data['attribute'] = $this->tourism_goods_category_attribute->getAttributeByCategoryId($goodsBase->category_id);
        $data['transport'] = $this->tourism_freight_template->getTransport($this->uid);
        $data['providerCategory'] = $this->tourism_provider_category->providerCategoryByUid($this->uid);
        $data['profitRate'] = $this->tourism_profit_rate->findByParams(array('uid'=>['in' => [$this->uid,0]]),'rate_id,uid,name',null,'rate_id');
        $data['id'] = $goods_attr_id;
        $this->load->view('tourismgoodsbase/edit', $data);
    }

     /**
     * 商品修改处理
     * author laona
     **/
    public function editPost()
    {
        $goods_attr_id = $this->input->post('goods_attr_id');
        $res = $this->tourism_goods_attr->findOne(['goods_attr_id' => $goods_attr_id]);
        if ($res->num_rows() <= 0) {
            $this->error('tourismgoodsbase/grid', '', '商品数据不存在');
        }
        $goodsattr = $res->row();
        $goodsRes = $this->tourism_goods_base->findOne(['uid' => $this->uid, 'goods_id' => $goodsattr->goods_id]);
        if ($goodsRes->num_rows() <= 0){
            $this->error('tourismgoodsbase/grid', '', '商品数据错误');
        }
        $newShopPrice = $this->input->post('shop_price');
        $newSupplyPrice = $this->input->post('supply_price');
        $error = $this->validate();
        if (!empty($error)) {
            $this->error('tourismgoodsbase/edit', $goods_attr_id, $error);
        }
        $postData = $this->input->post();
        $postData['uid'] = $this->uid;
        if ($postData['transport_type'] == 0) {
            $postData['transport_cost'] = 0;
        }
        $this->db->trans_begin();
        $goodsId = $this->tourism_goods_base->updateGoodsBase($postData);
        $attrId = $this->tourism_goods_attr->updateGoodsAttr($goods_attr_id, $postData);
        $profitState = $this->updateProfit($goodsattr,$newShopPrice,$newSupplyPrice,$goods_attr_id);
        if (!$profitState['status']) {
            $this->db->trans_rollback();
            $this->error('tourismgoodsbase/edit', $goods_attr_id, $profitState['msg']);
        }
        if ($goodsId && $attrId && $this->db->trans_status() === TRUE) {
            $this->db->trans_commit();
            $this->success('tourismgoodsbase/grid', '', '修改成功！');
        } else {
            $this->db->trans_rollback();
            $this->error('tourismgoodsbase/edit', $goods_attr_id, '修改失败！');
        }
    }

    /**
     * 分润表更新
     * */
    public function updateProfit($goodsattr,$newShopPrice,$newSupplyPrice,$goods_attr_id)
    {
        if ($goodsattr->shop_price != $newShopPrice || $goodsattr->supply_price != $newSupplyPrice){
            $profiteRes = $this->tourism_goods_profit->findOne(['goods_attr_id' => $goods_attr_id, 'status' => 1]);
            if ($profiteRes->num_rows() > 0){
                if (bccomp($newShopPrice - $newSupplyPrice,0.1,3) == -1) {
                    return ['status' => false, 'msg' => '销售价至少大于供应价0.1元'];
                }
                $count = $profiteRes->num_rows();
                $n = 1;
                $amountAdd = 0;
                foreach ($profiteRes->result() as $value) {
                    if ($value->uid != $this->uid) {
                        $amount = bcmul(bcdiv($value->amount, $goodsattr->shop_price - $goodsattr->supply_price,2), $newShopPrice - $newSupplyPrice,2);
                        if ($n == $count - 1) {
                            $amount = $newShopPrice - $newSupplyPrice - $amountAdd;
                        }
                        $profitState = $this->tourism_goods_profit->update(['amount' => $amount], ['goods_attr_id' => $goods_attr_id, 'uid' => $value->uid]);
                        if ($profitState == false) {
                            return ['status' => false, 'msg' => '修改失败'];
                        }
                        $amountAdd += $amount;
                        $n++;
                    }else {
                        if ($goodsattr->supply_price != $newSupplyPrice){
                            $profitState = $this->tourism_goods_profit->update(['amount' => $newSupplyPrice], ['goods_attr_id' => $goods_attr_id, 'uid' => $value->uid]);
                            if ($profitState == false) {
                                return ['status' => false, 'msg' => '修改失败'];
                            }
                        }
                    }
                }
            }
        }
        return ['status' => true];
    }
    
     /**
     * 商品删除
     * */
    public function delete($goods_id)
    {
        $params['goods_id'] = $goods_id;
        $params['uid'] = $this->uid;
        $this->error('tourismgoodsbase/grid', '', '目前商品数量过少,禁止删除');
        exit;
        $result = $this->tourism_goods_base->delete($params);
        if ($result) {
            $this->success('tourismgoodsbase/grid', '', '商品已删除');
        } else {
            $this->error('tourismgoodsbase/grid', '', '商品删除失败');
        }
    }

    /*
    *产品数据统计
    * */
    public function statistic()
    {
        $this->load->view('tourismgoodsbase/statistic');
    }

    /*
     *  订单编号
     * */
    public function number()
    {
        return date('ynjGis') . mt_rand(100, 999);
    }

    /*
     *获取商品类型
     * author laona
     * */
    public function get_good_spec($keys, $value)
    {
        if ($keys && $value) {
            foreach ($keys as $k => $key) {
                if (!isset($keys[$k]) || empty($keys[$k]) || !isset($value[$k]) || empty($value[$k])) {
                    unset($keys[$k]);
                    unset($value[$k]);
                }
            }
            return serialize(array_combine($keys, $value));
        }
        return '';
    }


    public function replaceContent()
    {
        $result = $this->tourism_goods_base->findByParams([], 'goods_id, wap_goods_desc');
        foreach ($result->result() as $item) {
            if (!empty($item->wap_goods_desc) && strpos($item->wap_goods_desc, 'img.miaocw.com') > 0) {
                $wap_goods_desc = str_replace('img.miaocw.com', 'img.zxkj918.com', $item->wap_goods_desc);
                $this->tourism_goods_base->update(['wap_goods_desc' => $wap_goods_desc], ['goods_id' => $item->goods_id]);
            }
        }
    }
}